package com.xbq.exceleditor.ui

import android.app.Activity
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.xbq.exceleditor.BuildConfig
import com.xbq.exceleditor.R
import com.xbq.exceleditor.databinding.FragmentRegisterBinding
import com.xbq.exceleditor.utils.validateEmpty
import com.xbq.exceleditor.utils.validateSame
import com.xbq.exceleditor.utils.value
import com.xbq.xbqsdk.component.activity.VBFragment
import com.xbq.xbqsdk.net.UserRepository
import com.xbq.xbqsdk.util.click.onDebouncedClick
import com.xbq.xbqsdk.util.coroutine.launch
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * Author: liaohaiping
 * Time: 2020-10-24
 * Description:
 */
@AndroidEntryPoint
class RegisterFragment : VBFragment<FragmentRegisterBinding>() {

    @Inject
    lateinit var userRepository: UserRepository

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initDebug()
        binding.let {
            it.etPhoneNumber.setHint(R.string.pls_type_user_name)
            CkbReadPrivacySetup(it.tvPrivacy).setup()
            it.btnBack.onDebouncedClick { (activity as LoginActivity?)?.showLogin() }
            it.btnGoLogin.onDebouncedClick { (activity as LoginActivity?)?.showLogin() }
            it.btnRegister.onDebouncedClick { register() }
            it.ckbReadPrivacyAlready.setOnCheckedChangeListener { buttonView, isChecked ->
                it.btnRegister.isEnabled = isChecked
            }
        }
    }

    fun initDebug() {
        if (BuildConfig.DEBUG) {
            binding.etPhoneNumber.setText("test")
            binding.etPassword.setText("123")
            binding.etPasswordConfirm.setText("123")
        }
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    fun register() {
        launch {
            val phone = binding.etPhoneNumber.value()
            val pwd = binding.etPassword.value()
            val pwdConfirm = binding.etPasswordConfirm.value()
            if (validateEmpty(phone, R.string.pls_type_user_name)
                && validateEmpty(pwd, R.string.pls_type_password)
                && validateEmpty(pwdConfirm, R.string.pls_type_password_confirm)
                && validateSame(pwd, pwdConfirm, R.string.twice_password_is_not_the_same)
            ) {
                val res = userRepository.registerAndLogin(phone, pwd)
                if (res.success()) {
                    ToastUtils.showShort("恭喜您！注册并登录成功")
                    activity?.setResult(Activity.RESULT_OK)
                    activity?.finish()
                } else {
                    ToastUtils.showShort(res.message)
                }
            }
        }
    }


}